<template>
    <div class="background" v-bind:style="{
        backgroundImage: 'url(' + backGroundImg + ')', position: fixed,
        backgroundRepeat: 'no-repeat', backgroundSize: '100% 17%'
    }">>
        <!-- @back="$router.go(-1)" -->
        <div style="color: rgb(255, 255, 255);margin-left: 20%;margin-top: 2%;display: inline-block;font-size: 2em;">
            <icon-font type="icon-fanhui" @click="$router.go(-1)"></icon-font>
        </div>
        <div style="margin-left: 0;margin-top: 2%;display: inline-block">

            <a-page-header title="注册" :sub-title="subtitle" />
        </div>
        <div class="page-wrapper">
            <a-card :bordered="true"
                style="width: 55%;height: 75vh;margin: 0 auto;background-color: rgb(247, 249, 252);border-radius: 2vh;">
                <!--    注册页-->
                <template v-if="step === 'register'">
                    <!--注册表单-->
                    <a-form :label-col="labelCol" :wrapper-col="wrapperCol">
                        <a-form-item v-bind="validateInfos.username" label="用户名称" style="margin-top: 5%;">
                            <a-input :id="domMap.register.username" v-model:value="modelRef.username" size="large"
                                style="width: 65%;" placeholder="请输入用户名" @blur="
                                    validate('username').catch((_error) => {
                                        logger.warn(_error)
                                    })
                                    " />
                        </a-form-item>
                        <a-form-item v-bind="validateInfos.password" label="密码" style="margin-top: 3%;">
                            <a-input-password :id="domMap.register.password" autocomplete v-model:value="modelRef.password"
                                size="large" style="width: 65%;" placeholder="请输入密码" @blur="
                                    validate('password').catch((_error) => {
                                        logger.warn(_error)
                                    })
                                    " />
                        </a-form-item>
                        <a-form-item v-bind="validateInfos.email" label="电子邮箱" style="margin-top: 3%;">
                            <a-input :id="domMap.register.email" v-model:value="modelRef.email" size="large"
                                placeholder="可稍后设置" style="width: 65%" @blur="
                                    validate('email').catch((_error) => {
                                        logger.warn(_error)
                                    })
                                    " />
                        </a-form-item>
                        <a-form-item v-bind="validateInfos.identity" label="职称信息" style="margin-top: 3%;">
                            <a-select :id="domMap.register.identity" v-model:value="modelRef.identity" size="large"
                                style="width: 65%;font-size: 1.2em;" placeholder="请选择" @blur="
                                    validate('identity').catch((_error) => {
                                        logger.warn(_error)
                                    })
                                    ">
                                <a-select-option v-for="item in identityOptions" :key="item.identityId"
                                    :value="item.identityId" :label="item.identityName">
                                    <span>
                                        {{ item.identityName }}
                                    </span>
                                </a-select-option>
                            </a-select>
                        </a-form-item>
                        <a-form-item :wrapper-col="{ span: 14, offset: 4 }">
                            <a-button :id="domMap.register.register" type="primary" @click.prevent="onSubmit"
                                style="border-radius: 20vh;margin-left: 30%;font-weight: bold;height: 4vh;width: 10vh;"
                                :loading="buttonLoading">注册</a-button>
                            <a-button :id="domMap.register.reset"
                                style="margin-left: 15%; font-weight: bold;border-radius: 20vh;height: 4vh;width: 10vh;"
                                @click="resetFields">重置</a-button>
                            <template #help>
                                <p style="color:rgb(30, 70, 129);margin-left: 10%;">
                                    <br />
                                    选择“<strong style="color: rgb(87, 150, 243);">注册</strong>”来完成注册，选择“<strong
                                        style="color: rgb(87, 150, 243);">重置</strong>”来清空表单以供重新填写。
                                </p>
                            </template>
                        </a-form-item>
                    </a-form>
                </template>
                <!--    注册等待页-->
                <template v-if="step === 'waiting'">
                    <a-result status="info" title="请稍候..." sub-title="一点点处理工作。" />
                </template>
                <!--    注册错误页-->
                <template v-if="step === 'error'">
                    <a-result status="error" title="错误">
                        <template #subTitle>{{ error }}</template>
                        <template #extra>
                            <a-button key="back" type="primary" @click="$router.go(-1)">返回 </a-button>
                        </template>
                    </a-result>
                </template>
                <!--    注册结果页-->
                <template v-if="step === 'done'">
                    <a-result status="success" title="注册完成">
                        <template #extra>
                            <a-button key="console" type="primary" @click="$router.push('/')">前往控制台 </a-button>
                        </template>
                    </a-result>
                </template>
            </a-card>
        </div>
    </div>
</template>

<script>
import { defineComponent, reactive, toRaw, toRefs, ref, onMounted } from 'vue'
import { validate_username } from '@/api/post/validate_username'
import { validate_email } from '@/api/post/validate_email'
import { register } from '@/api/post/register'
import { useStore } from 'vuex'
import { Form } from 'ant-design-vue'
import domMap from '@/constant/dom_map'
import logger from '@/util/logger'
import { identity_info } from '@/api/post/identity_info'
import { icon_url } from '@/util/iconfont'
import { createFromIconfontCN } from '@ant-design/icons-vue'

const IconFont = createFromIconfontCN({
    scriptUrl: icon_url

});

export default defineComponent({
    components: {
        IconFont,
    },


    setup() {
        const store = useStore()
        // prettier-ignore
        const state = reactive({
            step: 'register',                                           // 当前步骤
            subtitle: `请填写表单以注册`,                                // 副标题
            error: '',                                                  // 当前错误        
            backGroundImg: require('@/assets/background.png'),
        })
        // 下拉列表
        const identityOptions = reactive([])
        const buttonLoading = ref(false)
        // 表单模型
        const modelRef = reactive({
            username: '',
            password: '',
            email: '',
            identity: undefined,

        })

        onMounted(() => {
            initSelect()

        })
        // 下拉列表数据获取
        const initSelect = () => {
            identity_info().then((response) => {
                if (response.data.status.code === 0) {
                    let tmp = response.data.data;
                    for (let i = 0; i < tmp.length; i++) {//循环，选项的个数即为tmp的长度
                        identityOptions.push({
                            identityId: tmp[i].identityId,
                            identityName: tmp[i].identityName,
                        });
                    }
                }
            })

        }
        // 表单验证规则
        const rulesRef = reactive({
            username: [
                {
                    trigger: 'blur',
                    required: true,
                    message: '请输入用户名',
                    type: 'string',
                },
                {
                    trigger: 'blur',
                    max: 16,
                    message: '用户名长度上限为 16 字符',
                },
                {
                    trigger: 'blur',
                    message: '用户名已被占用',
                    validator: (rule, value) => {
                        return new Promise((resolve, reject) => {
                            if (value.length === 0) {
                                resolve()
                            }
                            validate_username(value).then((response) => {
                                const { code, message } = response.data.status
                                if (code === 0) {
                                    resolve()
                                } else {
                                    reject(message)
                                }
                            })
                        })
                    },
                },
            ],
            password: [
                {
                    required: true,
                    message: '请输入密码',
                },
                {
                    trigger: 'blur',
                    min: 8,
                    max: 16,
                    message: '密码长度必须在 8-16 字符之间',
                },
            ],
            email: [
                {
                    trigger: 'blur',
                    required: false,
                    message: '请输入有效的电子邮件地址',
                    type: 'email',
                },
                {
                    trigger: 'blur',
                    message: '电子邮件地址已被占用',
                    validator: (rule, value) => {
                        return new Promise((resolve, reject) => {
                            if (value.length === 0) {
                                resolve()
                            }
                            validate_email(value).then((response) => {
                                const { code, message } = response.data.status
                                if (code === 0) {
                                    resolve()
                                } else {
                                    reject(message)
                                }
                            })
                        })
                    },
                },
            ],
            identity: [
                {
                    trigger: 'blur',
                    required: true,
                    message: '请选择职称信息',
                }
            ],


        })
        const { resetFields, validate, validateInfos } = Form.useForm(modelRef, rulesRef)
        const onSubmit = () => {
            validate()
                .then(() => {
                    buttonLoading.value = {
                        delay: 500,
                    }
                    state.step = 'waiting'
                    const form = toRaw(modelRef)
                    register(form.email, form.username, form.password, form.identity).then((response) => {
                        if (response.data.status.code === 0) {
                            //注册成功
                            store.commit('CLEAR_USER_INFO')
                            store.commit('SET_TOKEN', response.data.data)
                            // 继续获取用户信息
                            setTimeout(() => {
                                store.dispatch('UPDATE_USER_INFO').then(() => {
                                    buttonLoading.value = false
                                    state.step = 'done'
                                })
                            }, 500)
                        } else {
                            state.step = 'error'
                            state.error = response.data.status.message
                        }
                    })
                })
                .catch((_error) => {
                    logger.warn(_error)
                })
        }
        return {
            ...toRefs(state),
            validateInfos,
            resetFields,
            modelRef,
            identityOptions,
            validate,
            onSubmit,
            initSelect,
            labelCol: {
                span: 8,
            },
            wrapperCol: {
                span: 14,
            },
            buttonLoading,
            domMap,
            logger,
        }
    },
})
</script>

<style scoped>
.page-wrapper {
    margin-top: 4%;
}

:deep(.ant-page-header-heading-title) {
    color: rgb(255 255 255);
    font-weight: 520;
    font-size: 2em;
}

:deep(.ant-page-header-heading-sub-title) {
    color: rgb(255, 255, 255);
    font-size: 1em;
    line-height: 1.5715;

}

:deep(.ant-page-header-back-button) {
    color: rgb(255, 255, 255);

}

:deep(.ant-form-item-label > label) {
    color: rgb(67, 82, 119);
    font-weight: 600;
}

:deep(.ant-input-password-icon) {
    color: rgb(158, 189, 252);
    cursor: pointer;
    transition: all 0.3s;
}
</style>